package com.twoscreen;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class TUserServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger("com.twoscreen.TUserServlet.java");
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
		log.info("Event POST message received.");
		
		int code = 0;
		String userName = null;
		
		if (request.getParameter("code") != null) {
			code = Integer.parseInt(request.getParameter("code"));
			log.info("code received: " + code);
		}
		if (request.getParameter("usern") != null) {
			userName = request.getParameter("usern");
			log.info("userName received: " + userName);
		}
		
		UserService userService = UserServiceFactory.getUserService();
		User user = null;
		try {
			user = userService.getCurrentUser();
		} catch (Exception e) {
			log.warning("Error getting the user: " + e);
		}
		
		
		switch (code) {
		
		case 1:
			//Validate username: if invalid create and return 5 suggestions - if valid save and return ok
			log.info("Validate and save username: " + userName);
			log.info("tuser check: " + TUser.checkUserName(userName) + " validator: " + Validator.validate(4, userName));
			Boolean valid = TUser.checkUserName(userName) && Validator.validate(4, userName);
			log.info("valid overall: " + valid);
			StringBuilder sb = new StringBuilder();
			sb.append("{\"status\": \"");
			
			if (valid && user != null) {
				try {
					TUser.saveUserName(user, userName);
					sb.append("ok\"}");
				} catch (Exception e) {
					log.warning("Error with saving username: " + e);
					sb.append("system_error\"}");
				}
			} else {
				if (user != null) {
					//Create the suggestions
					sb.append("in_use\", \"suggestions\": [");
					String[] suggestions = TUser.getUserNameSuggestions(userName);
					for (String suggestion : suggestions) {
						sb.append("\"" + suggestion.toString() + "\",");
					} 
					sb.deleteCharAt(sb.length()-1);
					sb.append("]}");
				} else {
					//No user is signed in
					sb.append("validation_error\"}");
				}
			}
			
			//Return the JSON
			String json = sb.toString();
			response.setContentType("application/json, charset=UTF-8");
			try {
				response.getWriter().println(json);
				log.info("Current events JSON sent");
			} catch (IOException e) {
				log.warning("Current events JSON response error: " + e);
			}
			
			break;
			
		default:
			break;
		
		}
		
		
	}

}
